//
//  gongNengBViewController.m
//  1243
//
//  Created by 我的 on 16/3/22.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "gongNengBViewController.h"
#import "NearBusinessCell.h"
#import "NearBusinessHeaderView.h"

#import "AFNetworking.h"

#import "UIImageView+WebCache.h"
#import "SweepViewController.h"
#import "ErWeiMaViewController.h"
#import "JudgeUserLogInTool.h"
#import "XRCarouselView.h"
#import "JSDropDownMenu.h"
#import "NetWorkTools.h"
#import "SVProgressHUD.h"

#import "ShopOneCollectionViewController.h"

#import "BZBViewController.h"

@interface gongNengBViewController ()<UITableViewDelegate, UITableViewDataSource, XRCarouselViewDelegate, JSDropDownMenuDataSource, JSDropDownMenuDelegate>{
    
    NSMutableArray *_data1;
    NSMutableArray *_data2;
    NSMutableArray *_data3;
    
    NSInteger _currentData1Index;
    NSInteger _currentData2Index;
    NSInteger _currentData3Index;
}

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NearBusinessHeaderView *nearBusinessHeaderView;

@property (nonatomic, strong) NSArray *shoperarray;

@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong) XRCarouselView *XRCarouselView;

@property (nonatomic, strong) JSDropDownMenu *menu;

@property (nonatomic,strong)NSMutableArray *imagesArray;

@end

@implementation gongNengBViewController

static NSString *ID = @"Cell";

- (void)loadView {
    [super loadView];
    [SVProgressHUD show];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [SVProgressHUD dismiss];
}

- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 155)];
        _headerView.backgroundColor = [UIColor grayColor];
    }
    return _headerView;
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
        
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"NearBusinessCell" bundle:nil] forCellReuseIdentifier:ID];
    
    [self ShopDatasources];
    
    [self setNavBarItem];
}

- (void)creatHeaderView {
    
    
//   __block NSMutableArray *imagesArray = [NSMutableArray array]
    
    
    self.XRCarouselView = [XRCarouselView carouselViewWithFrame:CGRectMake(0, 0, WIDTH, 150) imageArray:self.imagesArray];
    
    self.XRCarouselView.delegate = self;
    
    self.XRCarouselView.time = 2;
    
    [self.headerView addSubview:self.XRCarouselView];
    
    
    NSArray *food = @[@"选择分类", @"火锅", @"川菜", @"西餐", @"自助餐"];
    NSArray *travel = @[@"全部旅游", @"周边游", @"景点门票", @"国内游", @"境外游"];
    
    _data1 = [NSMutableArray arrayWithObjects:@{@"title":@"美食", @"data":food}, @{@"title":@"旅游", @"data":travel}, nil];
    
    NSArray *city = @[@"西湖区", @"下城区", @"上城区", @"萧山区"];
    _data2 = [NSMutableArray arrayWithObjects:@{@"title":@"全城", @"data":city}, nil];
    _data3 = [NSMutableArray arrayWithObjects:@"智能排序", @"离我最近", @"评价最高", @"最新发布", @"人气最高", @"价格最低", @"价格最高", nil];
    
    self.menu = [[JSDropDownMenu alloc] initWithOrigin:CGPointMake(0, 0) andHeight:45];
    self.menu.indicatorColor = [UIColor colorWithRed:175.0f/255.0f green:175.0f/255.0f blue:175.0f/255.0f alpha:1.0];
    self.menu.separatorColor = [UIColor colorWithRed:210.0f/255.0f green:210.0f/255.0f blue:210.0f/255.0f alpha:1.0];
    self.menu.textColor = [UIColor colorWithRed:83.f/255.0f green:83.f/255.0f blue:83.f/255.0f alpha:1.0f];
    self.menu.dataSource = self;
    self.menu.delegate = self;
    
    
}

#pragma mark - JSDropDownMenuDataSource
- (NSInteger)numberOfColumnsInMenu:(JSDropDownMenu *)menu {
    
    return 3;
}

-(BOOL)displayByCollectionViewInColumn:(NSInteger)column{
    
    if (column==2) {
        
        return YES;
    }
    
    return NO;
}

-(BOOL)haveRightTableViewInColumn:(NSInteger)column{
    
    if (column == 0 || column == 1) {
        return YES;
    }
    return NO;
}

-(CGFloat)widthRatioOfLeftColumn:(NSInteger)column{
    
    if (column==0 || column == 1) {
        return 0.3;
    }
    
    return 1;
}

-(NSInteger)currentLeftSelectedRow:(NSInteger)column{
    
    if (column==0) {
        
        return _currentData1Index;
        
    }
    if (column==1) {
        
        return _currentData2Index;
    }
    
    return 0;
}

- (NSInteger)menu:(JSDropDownMenu *)menu numberOfRowsInColumn:(NSInteger)column leftOrRight:(NSInteger)leftOrRight leftRow:(NSInteger)leftRow{
    
    if (column==0) {
        if (leftOrRight==0) {
            
            return _data1.count;
        } else{
            
            NSDictionary *menuDic = [_data1 objectAtIndex:leftRow];
            return [[menuDic objectForKey:@"data"] count];
        }
    } else if (column==1){
        if (leftOrRight==0) {
            
            return _data2.count;
        } else{
            
            NSDictionary *menuDic = [_data2 objectAtIndex:leftRow];
            return [[menuDic objectForKey:@"data"] count];
        }

        
    } else if (column==2){
        
        return _data3.count;
    }
    
    return 0;
}

- (NSString *)menu:(JSDropDownMenu *)menu titleForColumn:(NSInteger)column{
    
    switch (column) {
        case 0: return [[_data1[0] objectForKey:@"data"] objectAtIndex:0];
            break;
        case 1: return [[_data2[0] objectForKey:@"data"] objectAtIndex:0];
            break;
        case 2: return _data3[0];
            break;
        default:
            return nil;
            break;
    }
}

- (NSString *)menu:(JSDropDownMenu *)menu titleForRowAtIndexPath:(JSIndexPath *)indexPath {
    
    if (indexPath.column==0) {
        if (indexPath.leftOrRight==0) {
            NSDictionary *menuDic = [_data1 objectAtIndex:indexPath.row];
            return [menuDic objectForKey:@"title"];
        } else{
            NSInteger leftRow = indexPath.leftRow;
            NSDictionary *menuDic = [_data1 objectAtIndex:leftRow];
            return [[menuDic objectForKey:@"data"] objectAtIndex:indexPath.row];
        }
    } else if (indexPath.column==1) {
        if (indexPath.leftOrRight==0) {
            NSDictionary *menuDic = [_data2 objectAtIndex:indexPath.row];
            return [menuDic objectForKey:@"title"];
        } else{
            NSInteger leftRow = indexPath.leftRow;
            NSDictionary *menuDic = [_data2 objectAtIndex:leftRow];
            return [[menuDic objectForKey:@"data"] objectAtIndex:indexPath.row];
        }
    } else {
        
        return _data3[indexPath.row];
    }
}

#pragma mark - JSDropDownMenuDelegate
- (void)menu:(JSDropDownMenu *)menu didSelectRowAtIndexPath:(JSIndexPath *)indexPath {
    
    if (indexPath.column == 0) {
        
        if(indexPath.leftOrRight==0){
            
            _currentData1Index = indexPath.row;
            
            return;
        }
        
    } else if(indexPath.column == 1){
        if(indexPath.leftOrRight==0){
            
            _currentData2Index = indexPath.row;
            
            return;
        }
    } else{
        
        _currentData3Index = indexPath.row;
    }
}


#pragma mark - XRCarouselViewDelegate

- (void)carouselView:(XRCarouselView *)carouselView didClickImage:(NSInteger)index {
    NSLog(@"点击了第%ld张图片", index);
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"敬请期待" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//    [alert show];
    
    [self loadBannerImage];
    
    [self creatHeaderView];
    
}

- (void)loadBannerImage {
    NSDictionary *params = @{
                             @"Sort":@"",
                             @"MerchantId":@"1",
                             @"Type":@"1"
                             };
    self.imagesArray = [NSMutableArray array];
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"BANNERQUERY" completeBlock:^(id object) {
        NSLog(@"%@",object);
        
        NSString *string = [object objectForKey:@"BackData"];
        
        NSArray *array = [NetWorkTools arrayWithJsonString:string];
        
        for (int i = 0; i < array.count; i++) {
            
            NSString *url = @"http://120.76.162.124:8083";
            
            NSString *imageUrl = [NSString stringWithFormat:@"%@%@",url,array[i][@"Pic"]];
            
//            NSMutableArray *imagesArray = [NSMutableArray array];
            
            [self.imagesArray addObject:imageUrl];
            
        }
        
        self.XRCarouselView = [XRCarouselView carouselViewWithFrame:CGRectMake(0, 0, WIDTH, 150) imageArray:self.imagesArray];
        
        self.XRCarouselView.delegate = self;
        
        self.XRCarouselView.time = 2;
        
        [self.headerView addSubview:self.XRCarouselView];
        
//        NSLog(@"-----%@", self.imagesArray);
        
    }];
}
- (void)saoYiSaoBtn {
    if ([JudgeUserLogInTool  JudgeUserLonInStatus]) {
        SweepViewController *a = [[SweepViewController alloc] init];
        [self pushForm:self.navigationController pushToAndHidden:a];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        
        [alert show];
        
    }
}

- (void)fuKuanBtn {
    if ([JudgeUserLogInTool  JudgeUserLonInStatus]) {
        ErWeiMaViewController *a = [[ErWeiMaViewController alloc] init];
        [self pushForm:self.navigationController pushToAndHidden:a];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        
        [alert show];
        
    }
}
- (void)setNavBarItem {
    //// 扫一扫
       self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"nav_1"] highImage:[UIImage imageNamed:@"nav_1"] target:self action:@selector(saoYiSaoBtn) imageEdgeInsets:UIEdgeInsetsMake(0, -20, 15, -35) titleEdgeInsets:UIEdgeInsetsMake(20, -50, 0, 0) title:@"扫一扫"];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"nav_3"] highImage:[UIImage imageNamed:@"nav_3"] target:self action:@selector(fuKuanBtn) imageEdgeInsets:UIEdgeInsetsMake(0, 35, 15, -35) titleEdgeInsets:UIEdgeInsetsMake(20, 20, 0, 0) title:@"收款"];
    
    CGRect frame;
    if (WIDTH == 320) {
        frame = CGRectMake(-25, 0, 200, 30);
    } else {
        frame = CGRectMake(0, 0, 200, 30);
    }
    
    UIView *view = [[UIView alloc] initWithFrame:frame];
    
    UITextField *searchFeild = [[UITextField alloc] initWithFrame:frame];
    searchFeild.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入商家或者商品名称" attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    searchFeild.textColor = [UIColor redColor];
    searchFeild.font = [UIFont systemFontOfSize:14];
    searchFeild.layer.cornerRadius = searchFeild.frame.size.height/2;
    searchFeild.layer.masksToBounds = YES;
    searchFeild.enabled = NO;
    searchFeild.layer.borderWidth = 1;
    searchFeild.layer.borderColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1].CGColor;
    [self setLeftViewWithTextField:searchFeild imageName:@"nav_2"];
    [view addSubview:searchFeild];
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = searchFeild.frame;
    [searchBtn addTarget:self action:@selector(searchBut) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:searchBtn];
    
    self.navigationItem.titleView = view;
}

- (void)searchBut {
    NSLog(@"...");
}

- (void)dingWei {
    
}

//tabBar 隐藏
- (void)pushForm:(UINavigationController *)pushForm pushToAndHidden:(UIViewController *)pushToVC
{
    [pushToVC setHidesBottomBarWhenPushed:YES];
    [pushForm pushViewController:pushToVC animated:YES];
    
}

/**
 *  给UITextField设置右侧的图片
 *
 *  @param textField UITextField
 *  @param imageName 图片名称
 */

-(void)setLeftViewWithTextField:(UITextField *)textField imageName:(NSString *)imageName{
    
    UIImageView *rightView = [[UIImageView alloc]init];
    
    rightView.image = [UIImage imageNamed:imageName];
    rightView.frame = CGRectMake(0, 0, CGRectGetHeight(textField.frame), CGRectGetHeight(textField.frame));
    rightView.contentMode = UIViewContentModeCenter;
    
    textField.leftView = rightView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.backgroundColor = [UIColor blackColor];
    textField.alpha = 0.25;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark >>>>>>>> tableView dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }
    return self.shoperarray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NearBusinessCell *cell = [tableView dequeueReusableCellWithIdentifier:ID forIndexPath:indexPath];
    if (!cell) {
        cell = [[NearBusinessCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }

    NSString *string = [NSString stringWithFormat:@"http://120.76.162.124:8083%@", [self.shoperarray[indexPath.row] objectForKey:@"Logo"]];
    [cell.imageV sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:[UIImage imageNamed:@"shopZanweitu"]];
    cell.phoneLabel.text = [NSString stringWithFormat:@"固定电话: %@\n移动电话: %@",[self.shoperarray[indexPath.row] objectForKey:@"ContactPhone"],[self.shoperarray[indexPath.row] objectForKey:@"ContactMobile"]];
    cell.phoneLabel.numberOfLines = 0;
    cell.nameLabel.text = [self.shoperarray[indexPath.row] objectForKey:@"MerchantName"];
    cell.addressLabel.text = [NSString stringWithFormat:@"详细地址: %@",[self.shoperarray[indexPath.row] objectForKey:@"ContactAddress"]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 120;
}

#pragma mark - Table View Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    ShopsDetailViewController *shopdetailVC = [[ShopsDetailViewController alloc] init];
//    shopdetailVC.shopsID = [NSString stringWithFormat:@"%@", [self.shoperarray[indexPath.row] objectForKey:@"id"]];
//    [self.navigationController pushViewController:shopdetailVC animated:YES];
    
    BZBViewController *vc = [[BZBViewController alloc]init];
    
    [self pushForm:self.navigationController pushToAndHidden:vc];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return self.headerView;
    }
    return self.menu;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 155;
    }
    return 44;
}


#pragma mark  >>>>>>> 数据请求
- (void)ShopDatasources {
    
    NSDictionary *params = @{
                             @"Lot":@"31.220937",
                             @"Lat":@"121.4625",
                             @"Distance":@"500000.0",
                             @"Type":@"0",
                             @"ParentMerchantId":@"0"
                             };
    
    [[NetWorkTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"NEARMERCHANTQUERY" completeBlock:^(id object) {
        
        NSString *arrayString = [object objectForKey:@"BackData"];
        
        self.shoperarray = [NetWorkTools arrayWithJsonString:arrayString];
        
//        NSLog(@"%@",self.shoperarray);
        
        [self.tableView reloadData];
    }];      
        
}

- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}


@end
